package com.lingnan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingnan.dto.HrCreateJobPositionParam;
import com.lingnan.dto.HrJobStatisticsDto;
import com.lingnan.dto.JobPositionPageDto;
import com.lingnan.dto.JobPositionQueryParam;
import com.lingnan.entity.po.CompanyHr;
import com.lingnan.entity.po.JobApplication;
import com.lingnan.entity.po.JobPosition;
import com.lingnan.exception.MyException;
import com.lingnan.mapper.CompanyHrMapper;
import com.lingnan.mapper.JobApplicationMapper;
import com.lingnan.mapper.JobPositionMapper;
import com.lingnan.service.HrJobPositionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Transactional
public class HrJobPositionServiceImpl implements HrJobPositionService {
    
    @Autowired
    private JobPositionMapper jobPositionMapper;
    
    @Autowired
    private JobApplicationMapper jobApplicationMapper;
    
    @Autowired
    private CompanyHrMapper companyHrMapper;
    
    @Override
    public JobPositionPageDto createJobPosition(HrCreateJobPositionParam createParam, Long hrId, Long companyId) {
        // 参数验证
        if (hrId == null) {
            MyException.cast("HR信息不能为空");
        }
        if (companyId == null) {
            MyException.cast("公司信息不能为空");
        }
        
        // 验证HR是否属于该公司
        if (!validateHrBelongsToCompany(hrId, companyId)) {
            MyException.cast("HR与公司信息不匹配");
        }
        
        // 创建职位对象
        JobPosition jobPosition = new JobPosition();
        BeanUtils.copyProperties(createParam, jobPosition);
        jobPosition.setHrId(hrId);
        jobPosition.setCompanyId(companyId);
        jobPosition.setCreatedAt(new Date());
        jobPosition.setViewCount(0);
        
        // 保存职位
        boolean saveResult = jobPositionMapper.insert(jobPosition) > 0;
        if (!saveResult) {
            MyException.cast("职位创建失败");
        }
        
        // 返回完整职位信息
        return jobPositionMapper.selectJobPositionById(jobPosition.getId());
    }
    
    @Override
    public IPage<JobPositionPageDto> getHrPositions(int pageNum, int pageSize,
                                                    JobPositionQueryParam queryParam, Long hrId) {
        if (hrId == null) {
            MyException.cast("HR信息不能为空");
        }
        
        // 创建分页对象
        Page<JobPositionPageDto> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        QueryWrapper<JobPosition> queryWrapper = buildHrQueryWrapper(queryParam, hrId);
        
        // 执行查询
        return jobPositionMapper.selectJobPositionPage(page, queryWrapper);
    }
    
    @Override
    public JobPositionPageDto updateHrJobPosition(Long positionId, HrCreateJobPositionParam updateParam, Long hrId) {
        if (positionId == null) {
            MyException.cast("职位ID不能为空");
        }
        if (hrId == null) {
            MyException.cast("HR信息不能为空");
        }
        
        // 验证权限
        if (!checkHrPermission(positionId, hrId)) {
            MyException.cast("无权限操作该职位");
        }
        
        // 更新职位信息
        JobPosition jobPosition = new JobPosition();
        BeanUtils.copyProperties(updateParam, jobPosition);
        jobPosition.setId(positionId);
        jobPosition.setUpdatedAt(new Date());
        jobPosition.setUpdateId(hrId);
        
        boolean updateResult = jobPositionMapper.updateById(jobPosition) > 0;
        if (!updateResult) {
            MyException.cast("职位更新失败");
        }
        
        // 返回更新后的职位信息
        return jobPositionMapper.selectJobPositionById(positionId);
    }
    
    @Override
    public void deleteHrJobPosition(Long positionId, Long hrId) {
        if (positionId == null) {
            MyException.cast("职位ID不能为空");
        }
        if (hrId == null) {
            MyException.cast("HR信息不能为空");
        }
        
        // 验证权限
        if (!checkHrPermission(positionId, hrId)) {
            MyException.cast("无权限操作该职位");
        }
        
        // 检查是否有投递记录
        QueryWrapper<JobApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("position_id", positionId);
        Long applicationCount = jobApplicationMapper.selectCount(queryWrapper);
        
        if (applicationCount > 0) {
            MyException.cast("该职位已有投递记录，无法删除");
        }
        
        // 删除职位
        boolean deleteResult = jobPositionMapper.deleteById(positionId) > 0;
        if (!deleteResult) {
            MyException.cast("职位删除失败");
        }
    }
    
    @Override
    public HrJobStatisticsDto getHrJobStatistics(Long hrId) {
        if (hrId == null) {
            MyException.cast("HR信息不能为空");
        }
        
        return jobPositionMapper.selectHrJobStatistics(hrId);
    }
    
    @Override
    public boolean checkHrPermission(Long positionId, Long hrId) {
        if (positionId == null || hrId == null) {
            return false;
        }
        
        QueryWrapper<JobPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", positionId).eq("hr_id", hrId);
        return jobPositionMapper.selectCount(queryWrapper) > 0;
    }
    
    /**
     * 验证HR是否属于指定公司
     */
    private boolean validateHrBelongsToCompany(Long hrId, Long companyId) {
        QueryWrapper<CompanyHr> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", hrId).eq("company_id", companyId);
        return companyHrMapper.selectCount(queryWrapper) > 0;
    }
    
    /**
     * 构建HR查询条件
     */
    private QueryWrapper<JobPosition> buildHrQueryWrapper(JobPositionQueryParam queryParam, Long hrId) {
        QueryWrapper<JobPosition> queryWrapper = new QueryWrapper<>();
        
        // 必须是当前HR创建的职位
        queryWrapper.eq("jp.hr_id", hrId);
        
        if (queryParam != null) {
            if (StringUtils.hasText(queryParam.getTitle())) {
                queryWrapper.like("jp.title", queryParam.getTitle());
            }
            
            if (StringUtils.hasText(queryParam.getLocation())) {
                queryWrapper.like("jp.location", queryParam.getLocation());
            }
            
            if (StringUtils.hasText(queryParam.getSalaryRange())) {
                queryWrapper.eq("jp.salary_range", queryParam.getSalaryRange());
            }
            
            if (StringUtils.hasText(queryParam.getExpRequirement())) {
                queryWrapper.eq("jp.exp_requirement", queryParam.getExpRequirement());
            }
            
            if (StringUtils.hasText(queryParam.getType())) {
                queryWrapper.eq("jp.type", queryParam.getType());
            }
            
            if (StringUtils.hasText(queryParam.getEduRequirement())) {
                queryWrapper.eq("jp.edu_requirement", queryParam.getEduRequirement());
            }
            
            if (queryParam.getStatus() != null) {
                queryWrapper.eq("jp.status", queryParam.getStatus());
            }
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc("jp.created_at");
        
        return queryWrapper;
    }
}